package com.zl.tcbnewcar.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebActivity extends BaseActivity {

    @BindView(R.id.main_web)
    WebView webView;
    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_share)
    ImageView ivTitleShare;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    private String url;
    private String title;
    private String name;
    private boolean isFinish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        isFinish = getIntent().getBooleanExtra("isFinish", false);
        if (!TextUtils.isEmpty(title)) {
            tvTitleName.setText(title);
        }
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        //设置在本应用内打开网页
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.addJavascriptInterface(new JavaInterface(), "android");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();

    }

    @OnClick(R.id.iv_title_back)
    public void onViewClicked() {
        close();
    }

    private void close() {
        if (isFinish) {
            finish();
            return;
        }
        if (!TextUtils.isEmpty(name)) {
            //进入首页
            startActivity(new Intent(mActivity, MainActivity.class));
            finish();
        } else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            close();
        }
        return true;
    }

    private class JavaInterface {
        /**
         * 吊起分享功能
         */
        @JavascriptInterface
        public void finish() {
            WebActivity.this.finish();
        }
    }
}
